package com.iplatform.commons.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iplatform.commons.custom.LoginedAuth;
import com.iplatform.commons.utils.UserUtil;
import com.iplatform.module.privilege.PriManagerBean;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


public class LoginedAuthInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        final HandlerMethod handlerMethod = (HandlerMethod) handler;
        final Class<?> clazz = handlerMethod.getBeanType();
        final Method method = handlerMethod.getMethod();
        if (clazz.isAnnotationPresent(LoginedAuth.class) || method.isAnnotationPresent(LoginedAuth.class)) {
        	 String token =request.getParameter(OAuth2AccessToken.ACCESS_TOKEN);
             if (StringUtils.isEmpty(token)) {
                 throw new Exception("无效的验证凭证");
             }
             PriManagerBean priManagerBean = UserUtil.getLoginAppUser();
             request.setAttribute("currentUser", priManagerBean);
        }
        PriManagerBean priManagerBean = UserUtil.getLoginAppUser();
        request.setAttribute("currentUser", priManagerBean);
        return true;
	}



}
